//
//  SchoolDetailViewController.swift
//  HoneyBee
//
//  Created by point on 2018/1/29.
//  Copyright © 2018年 point. All rights reserved.
//

import UIKit
import SnapKit
import Photos
import MJRefresh
import SwiftyJSON

private let kBannerCellID = "SchoolDetailBannerTableViewCell"
private let kBaiscCellID = "SchoolDetailBasicTableViewCell"
private let kAdressCellID = "SchoolDetailAdressTableViewCell"
private let kActiveCellID = "SchoolDetailActivityTableViewCell"
private let kContentCellID = "SchoolDetailContentTableViewCell"
private let kCommentCellID = "SchoolDetailCommentTableViewCell"

class SchoolDetailViewController: BaseViewController {
    private var disposal = Disposal()
    var schoolID:String = ""
    fileprivate lazy var commentTitleView: SchoolDetailTitleView = SchoolDetailTitleView()
    /// 底部视图
    fileprivate lazy var bottomView: SchoolDetailBottomView = SchoolDetailBottomView()
    fileprivate var viewModel:SchoolDetailViewModel = SchoolDetailViewModel()
    
    fileprivate lazy var tableView : UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        return tableView
    }()
    
    fileprivate lazy var maskView = UIView()
    
    
    /// 弹出页面
    fileprivate lazy var  presentAimator:PresentAnimator = PresentAnimator()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        viewModel.loadData(schoolID)
        httpAddObserver()
        self.navigationController?.delegate = self
    }
    
    deinit {
        debugPrint("deinit: 详情页移除")
    }
}



// MARK: - 点击显示图片
extension SchoolDetailViewController :  SchoolDetailBannerTableViewCellDelegate {
    func bannerCycleViewDidScrollToIndex(_ index: Int) {
        let model = self.viewModel.model.value.schoolDetailResourceModel[index]
        if model.fileType == 0 {
            let vc = DetailEnlargeViewController()
            vc.modalPresentationStyle = .custom
            vc.imgStr = model.path
            vc.myframe = CGRect(x: 0, y: (kScreenH - kScreenW) / 2, width: kScreenW, height: kScreenW)
            self.presentAimator.presntFrame = CGRect(x: 0, y:0, width: kScreenW, height: kScreenH)
            vc.transitioningDelegate = self.presentAimator
            self.present(vc, animated: true, completion: nil)
        }else {
            let videoPath:String = String(model.path.split(separator: "?")[0])
            guard let playerURL = URL(string: videoPath) else { return }
            guard let vc = SHBAVController(url: playerURL) else {return }
            self.present(vc, animated: true, completion: nil)
        }
    }
}


// MARK: - 逻辑代码
extension SchoolDetailViewController : SchoolDetailContentTableViewCellDelegate , SchoolDetailBottomViewTDelegate , SchoolDetailCommentTableViewCellDelegate {
    
    func commentShowImgView(index: IndexPath, ImgIndex: IndexPath) {
        var tempArr:[String] = [String]()
        
        
        for val in viewModel.model.value.commentArr[index.item].resource {
            if val.path.count > 0 {
                tempArr.append(val.path)
            }else {
                tempArr.append("")
            }
        }
        
        let vc = PictureBrowserViewController(indexPath: ImgIndex, modelArr:tempArr)
        vc.modalPresentationStyle = .custom
        self.presentAimator.presntFrame = CGRect(x: 0, y:0, width: kScreenW, height: kScreenH)
        vc.transitioningDelegate = self.presentAimator
        self.present(vc, animated: true, completion: nil)
    }
    
    func loadComment(_ str: String) {
        TempNetTool.get( kHost + "/comment/queryCommentForInstitutionList?id=\(str)&pageNo=1&pageSize=10&timestamp=111&sign=111", parameters: nil, progress: nil, success: { [unowned self](commentResult) in
            let json = JSON(commentResult ?? "")
            var arr:[SchoolDetailCommentModel] = [SchoolDetailCommentModel]()
            let resourceArray = json["data"].arrayValue
            for resourceJson in resourceArray{
                let value = SchoolDetailCommentModel(fromJson: resourceJson)
                arr.append(value)
            }
            self.viewModel.currentModel.commentArr = arr
            self.viewModel.page = 2
            self.tableView.mj_footer.resetNoMoreData()
            self.tableView.reloadData()
        }) { (error) in
            
        }
    }
    
    func clickAction(_ type: SchoolDetailBottomViewType) {
        
        if type == .comment {
            
            if viewModel.currentModel.isComment == false {
                hudLoadMessage("机构确认后 , 才能评论")
                return
            }
            
            let vc = SchoolDetailViewCommentController()
            vc.backBlock = { [weak self] in
                self?.loadComment((self?.schoolID)!)
            }
            vc.schoolID = schoolID
            self.navigationController?.pushViewController(vc, animated: true)
            
        }else if (type == .tel) {
            let alertVC : UIAlertController = UIAlertController.init(title: "是否拨打", message: "", preferredStyle: .alert)
            let falseAA : UIAlertAction = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
            let trueAA : UIAlertAction = UIAlertAction.init(title: "确定", style: .default) { (alertAction) in
                guard let uid:String = UIDevice.current.identifierForVendor?.uuidString else { return }
                let url = kHost + kuserCallInstitution + String().apiF(time: "1", sign: "1") + "&id=\(self.schoolID)" + "&phoneKey=" + uid
                
                self.hudLoad()
                TempNetTool.post(url, parameters: nil, progress: nil, success: {[weak self] (result) in
                    self?.hudHide()
                    UIApplication.shared.open(NSURL.init(string: "tel://\(String(describing: self?.viewModel.model.value.phone))")! as URL, options: [:], completionHandler: nil)
                    }, failure: { [weak self](error) in
                        self?.hudHide()
                        self?.hudError()
                })
            }
            alertVC.addAction(falseAA)
            alertVC.addAction(trueAA)
            self.present(alertVC, animated: true, completion: nil)
        }else if (type == .collection) { //收藏
            
            
            
            self.hudLoad()
            let dict = [
                "userId":String(UserInfo.shareInstance.userModel().id),
                "id":self.schoolID,
                "timestamp":"1",
                "sign":"1"
            ]
            
            if self.viewModel.model.value.collection == false {
                TempNetTool.post( kHost + kaddCollectionInstitution + "".apiF(time: "1", sign: "1") + "&id=\(schoolID)" , parameters: dict, progress: nil, success: { [weak self](result) in
                    self?.hudHide()
                    self?.hudLoadMessage("收藏成功")
                    self?.viewModel.model.value.collection = true
                    self?.bottomView.collectionBtn.setImage(UIImage(named: "school_collection_secelted"), for: .normal)
                }) { [weak self] (error) in
                    self?.hudHide()
                    self?.hudLoadMessage("收藏失败")
                }
            }else {
                cancelCollectionInstitution()
            }
            
            
        }else if (type == .appointment) { //预约
            if self.viewModel.model.value.appointment == false {
                appointment()
            }else {
                cancelApointment()
            }
            
            
        }
    }
    
    func cancelCollectionInstitution() {
        TempNetTool.post(kHost + kcancelCollectionInstitution + "".apiF(time: "1", sign: "1") + "&id=\(schoolID)" , parameters: nil, progress: nil, success: { [weak self](result) in
            self?.hudHide()
            self?.viewModel.model.value.collection = false
            self?.bottomView.collectionBtn.setImage(UIImage(named: "school_collection"), for: .normal)
        }) { [weak self] (error) in
            self?.hudHide()
            self?.hudLoadMessage("取消收藏失败")
        }
    }
    
    func cancelApointment() {
        guard let uid:String = UIDevice.current.identifierForVendor?.uuidString else { return }
        TempNetTool.post( kHost + kcancelAppointmentInstitution + "".apiF(time: "1", sign: "1") + "&id=\(schoolID)" + "&phoneKey=" + uid, parameters: nil, progress: nil, success: { [weak self] (result) in
            self?.hudHide()
            self?.hudLoadMessage("取消预约成功")
            self?.bottomView.appointmentBtn.backgroundColor = UIColor.init(hex: "888896")
            self?.viewModel.model.value.appointment = false
            self?.bottomView.appointmentBtn.setTitle("预约试听", for: .normal)
            
        }) {[weak self]   (error) in
            self?.hudHide()
            self?.hudLoadMessage("取消预约失败")
        }
    }
    
    func appointment() {
        
        
        self.hudLoad()
        guard let uid:String = UIDevice.current.identifierForVendor?.uuidString else { return }
        let dict = [
            "userId":String(UserInfo.shareInstance.userModel().id),
            "id":self.schoolID,
            "phoneKey":uid,
            "timestamp":"1",
            "sign":"1"]
        
        
        TempNetTool.post( kHost + kaddAppointmentInstitution + "".apiF(time: "1", sign: "dd") + "&id=\(self.schoolID)" + "&phoneKey=" + uid , parameters: dict, progress: nil, success: { [weak self] (result) in
            self?.hudHide()
            self?.hudLoadMessage("预约成功")
            self?.viewModel.model.value.appointment = true
            self?.bottomView.appointmentBtn.backgroundColor = UIColor.init(hex: "17bbfe")
            self?.bottomView.appointmentBtn.setTitle("取消预约", for: .normal)
        }) {[weak self]   (error) in
            self?.hudHide()
            self?.hudLoadMessage("预约失败")
        }
        
    }
    
    //刷新
    func heightReload() {
        let indexPath = IndexPath(item:0 , section: 1)
        self.tableView.reloadRows(at: [indexPath], with: .none)
    }
    
    func commentReloadHeight(index: IndexPath) {
        self.tableView.reloadRows(at: [index], with: .none)
    }
}

// MARK:- 网络请求
extension SchoolDetailViewController {
    func httpAddObserver (){
        viewModel.model.observe { [weak self] (cur, pre) in
            if self?.viewModel.status == ViewModelStatus.none {
                self?.hudLoad()
            }
            
            if self?.viewModel.status == ViewModelStatus.ok {
                self?.hudHide()
                self?.tableView.reloadData()
                let time: TimeInterval = 0.4
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
                    self?.maskView.isHidden = true
                }
                
                if (self?.viewModel.model.value.collection)! {
                    self?.bottomView.collectionBtn.setImage(UIImage(named: "school_collection_secelted"), for: .normal)
                }else {
                    self?.bottomView.collectionBtn.setImage(UIImage(named: "school_collection"), for: .normal)
                }
                
                if (self?.viewModel.model.value.appointment)! {
                    self?.bottomView.appointmentBtn.backgroundColor = UIColor.init(hex: "17bbfe")
                    self?.bottomView.appointmentBtn.setTitle("取消预约", for: .normal)
                }else {
                    self?.bottomView.appointmentBtn.backgroundColor = UIColor.init(hex: "888896")
                    self?.bottomView.appointmentBtn.setTitle("预约试听", for: .normal)
                    
                }
                
            }
            
            if self?.viewModel.status == ViewModelStatus.error {
                self?.hudHide()
            }
            
            if self?.viewModel.status == ViewModelStatus.more {
                self?.tableView.mj_footer.endRefreshing()
                self?.tableView.reloadData()
            }
            if self?.viewModel.status == ViewModelStatus.done {
                self?.tableView.mj_footer.endRefreshingWithNoMoreData()
            }
            }.add(to: &disposal)
    }
    
    func configUI() {
        
    }
}

// MARK:- tableView 代理
extension SchoolDetailViewController:UITableViewDataSource,UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 { // 详情以上
            return 4
        } else if section == 1 { //详情
            return 1
        }else { //评论
            return viewModel.model.value.commentArr.count
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headview = SchoolDetailTitleView()
        
        if section == 1 {
            headview.titleLabel.text = "机构详情"
        }else if section == 2 {
            headview.titleLabel.text = "家长点评"
        }else {
            return nil
        }
        return headview
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 0.001
        }else {
            return 44
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            if (indexPath.item == 0) { //banner
                let cell = tableView.dequeueReusableCell(withIdentifier: kBannerCellID, for: indexPath) as! SchoolDetailBannerTableViewCell
                cell.delegate = self
                cell.configModel(model: viewModel.model.value)
                return cell
            }else if (indexPath.item == 1){ //简介
                let cell = tableView.dequeueReusableCell(withIdentifier: kBaiscCellID, for: indexPath) as! SchoolDetailBasicTableViewCell
                cell.configModel(model: viewModel.model.value)
                return cell
            }else if (indexPath.item == 2){ //地址
                let cell = tableView.dequeueReusableCell(withIdentifier: kAdressCellID, for: indexPath) as! SchoolDetailAdressTableViewCell
                cell.configModel(model: viewModel.model.value)
                return cell
            }else if (indexPath.item == 3){ //活动
                let cell = tableView.dequeueReusableCell(withIdentifier: kActiveCellID, for: indexPath) as! SchoolDetailActivityTableViewCell
                cell.configModel(model: viewModel.model.value)
                return cell
            }
        }
        
        if indexPath.section == 1 { //机构详情
            let cell = tableView.dequeueReusableCell(withIdentifier: kContentCellID, for: indexPath) as! SchoolDetailContentTableViewCell
            cell.configModel(model: viewModel.model.value)
            cell.delegate = self
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: kCommentCellID, for: indexPath) as! SchoolDetailCommentTableViewCell
        cell.delegate = self
        cell.configModel(model: viewModel.model.value.commentArr, index: indexPath)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                return  snapKitFit(190) //banner
            }else if (indexPath.row == 1) { //简介
                return   viewModel.model.value.basicCellHeight
            }else if (indexPath.row == 2) { //详细地址
                return snapKitFit(45)
            }else if (indexPath.row == 3) { //优惠活动
                return snapKitFit(45)
            }
        }
        
        if indexPath.section == 1 { //详情
            return viewModel.model.value.detailCellHeight
        }
        
        if indexPath.section == 2 { //评论
            let cellHeight = viewModel.model.value.commentArr[indexPath.item].cellHeight
            if viewModel.model.value.commentArr[indexPath.item].resource.count > 0{
                return  cellHeight + 150
            }else {
                return cellHeight + 50
            }
            
        }
        return 0
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            if (indexPath.row == 2) { //详细地址
                let vc = SchoolMapViewController()
                
                let model = SchoolModel()
                let userModel = UserInfo.shareInstance.userModel()
                model.longitude = self.viewModel.currentModel.longitude
                model.latitude = self.viewModel.currentModel.latitude
                model.name = self.viewModel.currentModel.name
                vc.modelArr = [model]
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
}

// MARK:- 设置UI
extension SchoolDetailViewController {
    fileprivate func setupUI(){
        view.backgroundColor = UIColor.white
        view.addSubview(tableView)
        view.addSubview(bottomView)
        
        tableView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(LayoutCommon.navHeight)
            make.left.right.equalTo(view)
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            } else {
                make.bottom.equalTo(view.snp.bottom)
            }
        }
        
        self.title = "机构详情"
        tableView.register(SchoolDetailBannerTableViewCell.self, forCellReuseIdentifier: kBannerCellID)
        tableView.register(SchoolDetailBasicTableViewCell.self, forCellReuseIdentifier: kBaiscCellID)
        tableView.register(SchoolDetailAdressTableViewCell.self, forCellReuseIdentifier: kAdressCellID)
        tableView.register(SchoolDetailActivityTableViewCell.self, forCellReuseIdentifier: kActiveCellID)
        tableView.register(SchoolDetailContentTableViewCell.self, forCellReuseIdentifier: kContentCellID)
        tableView.register(SchoolDetailCommentTableViewCell.self, forCellReuseIdentifier: kCommentCellID)
        tableView.separatorStyle = .none
        tableView.backgroundColor = UIColor.white
        
        bottomView.snp.makeConstraints { (make) in
            make.left.right.equalTo(view)
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            } else {
                make.bottom.equalTo(view)
            }
            make.height.equalTo(45)
        }
        bottomView.delegate = self
        bottomView.backgroundColor = UIColor.white
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: { [weak self] in
            self?.viewModel.commentLoadDataMore(self?.schoolID ?? "")
        })
        bottomView.isHidden = true
        
        
        view.addSubview(maskView)
        maskView.backgroundColor = UIColor.white
        maskView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(LayoutCommon.navHeight + snapKitFit(190) + 80)
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).inset(45)
            } else {
                make.bottom.equalTo(view).inset(45)
            }
        }
        
    }
}

// MARK:- 导航栏消失
extension SchoolDetailViewController: UINavigationControllerDelegate {
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        //self.navigationController?.setNavigationBarHidden(viewController is SchoolDetailViewController, animated: true)
    }
    
}
